const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  const { roomId, userInfo } = event.data
  const player = {
    openid,
    nickName: userInfo.nickName,
    avatarUrl: userInfo.avatarUrl,
    seat: 0,
    isOnline: true,
    isDrawing: false,
    score: 0
  }
  // 先查询该玩家是否已在该房间内
  const getResult = await db.collection('room').where({
    _id: roomId,
    'players.openid': openid
  }).get()
  if (!getResult.data.length) {
    await db.collection('room').doc(roomId).update({
      data: {
        players: db.command.push(player)
      }
    })
  }
  return db.collection('room').doc(roomId).get()
}